<template>
  <div>
    <!-- 操作按钮 -->
    <div
      style="
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
      "
    >
      <div>
        <a-button type="primary" @click="showModal" style="margin-right: 10px">
          新增
        </a-button>
        <a-button type="primary" danger @click="deleteSelect">删除</a-button>
      </div>
      <div style="display: flex; align-items: center">
        <!-- 多个搜索框与按钮在同一行显示 -->
        <a-input
          v-model:value="query.name"
          placeholder="名称"
          style="width: 100px; margin-right: 10px"
        />
        <!-- 查询按钮 -->
        <a-button
          type="primary"
          @click="handleTableChange"
          style="margin-right: 10px"
        >
          查询
        </a-button>
        <a-button type="primary" @click="clearSearch">清空</a-button>
      </div>
    </div>

    <!-- 表格 -->
    <a-table
      :columns="columns"
      :row-key="(record) => record.id"
      :data-source="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
    >
      <!-- 使用插槽来渲染操作列 -->
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <span>
            <a @click="update(record.id)">编辑</a>
            <a-divider type="vertical" />
            <a @click="_delete(record.id)">删除</a>
          </span>
        </template>
      </template>
    </a-table>
    <!-- 新增/修改 -->
    <a-modal
      width="40%"
      v-model:open="visible"
      title="新增参数"
      centered
      @ok="add"
      wrap-class-name="full-modal"
    >
      <form>
        <a-form
          :model="formData"
          :label-col="{ style: { width: '100px' } }"
          :wrapper-col="{ span: 24 }"
        >
          <a-form-item
            label="参数名称"
            :rules="[{ required: true, message: '请输入参数名称!' }]"
          >
            <a-input
              v-model:value="formData.name"
              placeholder="请输入参数名称"
            />
          </a-form-item>

          <!-- 背景图 -->
          <template v-if="CONFIG_KEY.BACKGROUND_LIST === formData.name">
            <a-row
              v-for="(item, index) in formData.valueArr"
              :key="index"
              @click="clickRow(index)"
            >
              <a-col :span="18" style="text-align: right">
                <a-form-item :label="'值' + index">
                  <a-input
                    v-model:value="item.value"
                    placeholder="请输入预览图"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="4" style="text-align: right">
                <a-upload
                  v-model:file-list="fileList"
                  name="image"
                  @change="handleChange"
                  class="avatar-uploader"
                  :show-upload-list="false"
                  :before-upload="beforeUpload"
                >
                  <a-button
                    style="background-color: #f0f0f0; margin-right: 22px"
                  >
                    图片上传
                  </a-button>
                </a-upload>
              </a-col>
              <a-col :span="2" style="text-align: right">
                <a-button @click="removeValue(item)">删除</a-button>
              </a-col>
            </a-row>
            <a-button
              style="display: block; margin: 0 auto; margin-bottom: 20px"
              @click="addValue()"
            >
              新增
            </a-button>
          </template>
          <!-- 网页脚本 -->
          <template
            v-else-if="
              CONFIG_KEY.WEBSITE_SCRIPT === formData.name ||
              CONFIG_KEY.WEBSITE_HEAD === formData.name
            "
          >
            <a-row
              v-for="(item, index) in formData.valueArr"
              :key="index"
              @click="clickRow(index)"
            >
              <a-col :span="21" style="text-align: right">
                <a-form-item :label="'代码' + index">
                  <a-input
                    v-model:value="item.value"
                    placeholder="请输入代码"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="3" style="text-align: right">
                <a-button @click="removeValue(item)">删除</a-button>
              </a-col>
            </a-row>
            <a-button
              style="display: block; margin: 0 auto; margin-bottom: 20px"
              @click="addValue()"
            >
              新增
            </a-button>
          </template>
          <!-- 默认参数 -->
          <template v-else>
            <template
              v-if="
                [CONFIG_KEY.DEFAULT_AVATAR, CONFIG_KEY.DEFAULT_IMAGE].indexOf(
                  formData.name
                ) > -1
              "
            >
              <a-row>
                <a-col :span="18" style="text-align: right">
                  <a-form-item
                    label="参数值"
                    :rules="[{ required: true, message: '请输入参数值!' }]"
                  >
                    <a-input
                      v-model:value="formData.value"
                      placeholder="请输入预览图"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="6" style="text-align: right">
                  <a-upload
                    v-model:file-list="fileList"
                    name="image"
                    @change="handleChange"
                    class="avatar-uploader"
                    :show-upload-list="false"
                    :before-upload="beforeUpload"
                  >
                    <a-button
                      style="background-color: #f0f0f0; margin-right: 22px"
                    >
                      图片上传
                    </a-button>
                  </a-upload>
                </a-col>
              </a-row>
            </template>

            <template v-else>
              <a-form-item
                label="参数值"
                :rules="[{ required: true, message: '请输入参数值!' }]"
              >
                <a-input
                  v-model:value="formData.value"
                  placeholder="请输入参数值"
                />
              </a-form-item>
            </template>
          </template>

          <a-form-item label="参数类型" name="type">
            <a-select
              v-model:value="formData.type"
              placeholder="请选择你的类型"
            >
              <a-select-option value="1">全局变量</a-select-option>
              <a-select-option value="2">系统变量</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
            label="描述"
            :rules="[{ required: false, message: '请输入描述!' }]"
          >
            <a-input
              v-model:value="formData.description"
              placeholder="请输入描述"
            />
          </a-form-item>
        </a-form>
      </form>
    </a-modal>
  </div>
</template>

<script>
  import { getList, _delete, add, get, update } from '@/api/config'
  import { Modal } from 'ant-design-vue'
  import moment from 'moment'
  import { fileUpload } from '@/api/common'

  // 一些特殊处理的cofig key
  const CONFIG_KEY = {
    WEBSITE_SCRIPT: 'WEBSITE_SCRIPT', // 站点脚本
    WEBSITE_HEAD: 'WEBSITE_HEAD', // 头部插入的代码
    BACKGROUND_LIST: 'BACKGROUND_LIST', // 背景图列表
    DEFAULT_AVATAR: 'DEFAULT_AVATAR', // 默认头像
    DEFAULT_IMAGE: 'DEFAULT_IMAGE', // 文章没有上传图片默认缩略图
  }

  // 定义列的字段
  const columns = [
    {
      title: '参数名',
      dataIndex: 'name',
    },
    {
      title: '参数值',
      dataIndex: 'value',
      ellipsis: true,
    },
    {
      title: '参数类型',
      dataIndex: 'type',
      key: 'type',
      customRender: ({ text }) => (text === 1 ? '全局变量' : '系统变量'),
    },
    {
      title: '描述',
      dataIndex: 'description',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      customRender: (text) => {
        return moment(text.value).format('YYYY-MM-DD HH:mm:ss')
      },
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      customRender: (text) => {
        if (text.value) {
          return moment(text.value).format('YYYY-MM-DD HH:mm:ss')
        } else {
          return text.value
        }
      },
    },
    {
      title: '操作',
      key: 'action', // 自定义渲染操作列
      fixed: 'right', // 固定右侧
    },
  ]
  export default {
    data() {
      return {
        data: [], // 列表数据
        pagination: {
          showLessItems: true,
          showQuickJumper: true,
          showSizeChanger: true,
        }, // 分页参数
        query: {}, //查询参数
        loading: false, // 是否加载
        columns, // 表格列
        selectedRowKeys: [], // 选中的列
        visible: false, // 显示新增修改框
        formData: {}, // 新增修改的数据框
        CONFIG_KEY: CONFIG_KEY,
        clickIndex: null,
      }
    },
    computed: {
      hasSelected() {
        return this.selectedRowKeys.length > 0
      },
    },
    mounted() {
      this.fetch()
    },
    methods: {
      // 记录点击当前行
      clickRow(index) {
        console.log(index)
        this.clickIndex = index
      },
      addValue(val) {
        this.formData.valueArr.push({
          value: val || '',
        })
      },
      removeValue(item) {
        var index = this.formData.valueArr.indexOf(item)
        if (index !== -1) {
          this.formData.valueArr.splice(index, 1)
        }
      },
      handleChange(info) {
        if (info.file.status === 'uploading') {
          this.loading = true
        }
        if (info.file.status === 'done') {
          // 上传完成后的操作
          this.loading = false

          // 从后台返回的响应中获取文件访问路径
          const response = info.file.response
          if (response && response.url) {
            this.formData.avatar = response.url
          }
        }
        if (info.file.status === 'error') {
          // 上传出错时的操作
          this.loading = false
        }
      },
      // 上传图片
      beforeUpload(file) {
        const formData = new FormData()
        formData.append('image', file)
        formData.append('label', 'config')
        fileUpload(formData).then((data) => {
          this.formData.valueArr[this.clickIndex].value = data.data
        })
        return true
      },
      // 打开新增框
      showModal() {
        this.visible = true
        this.formData = { type: '1' }
      },
      // 修改数据
      update(id) {
        get({ id: id }).then(({ data }) => {
          data.valueArr = []
          // 对返回的参数进行解构
          this.formData = { ...data }
          //   特殊处理单选项，ant只能接受字符串
          this.formData.type = this.formData.type + ''

          if (this.formData.name === CONFIG_KEY.BACKGROUND_LIST) {
            const valueArr = JSON.parse(this.formData.value)
            for (const val of valueArr) {
              this.addValue(val)
            }
          } else if (this.formData.name === CONFIG_KEY.WEBSITE_SCRIPT) {
            const reg = /<script[^>]*?>([\s\S]*?)<\/script>/g
            const valueArr = this.formData.value.match(reg)
            for (const val of valueArr) {
              this.addValue(val)
            }
          } else if (this.formData.name === CONFIG_KEY.WEBSITE_HEAD) {
            const reg =
              /(<meta[^>]*?>)|(<link[^>]*?>)|(<style[^>]*?>([\s\S]*?)<\/style>)|(<script[^>]*?>([\s\S]*?)<\/script>)/g
            const valueArr = this.formData.value.match(reg)
            for (const val of valueArr) {
              this.addValue(val)
            }
          }

          this.visible = true
        })
      },
      // 选择
      onSelectChange(selectedRowKeys) {
        console.log('selectedRowKeys changed: ', selectedRowKeys)
        this.selectedRowKeys = selectedRowKeys
      },
      // 删除选中
      deleteSelect() {
        this._delete(this.selectedRowKeys)
      },
      // 删除数据
      _delete(id) {
        let ids
        // 此处批量跟单个删除公用，做一下判断
        if (Array.isArray(id)) {
          ids = id
        } else {
          ids = [id]
        }
        if (ids && ids.length > 0) {
          Modal.confirm({
            title: 'Confirm',
            content: '确定要删除吗？',
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
              _delete(ids).then(() => {
                // 删除就清空勾选项
                this.selectedRowKeys = []
                // 重新查询数据
                this.handleTableChange(this.pagination)
              })
            },
          })
        }
      },
      // 清空查询参数
      clearSearch() {
        Object.getOwnPropertyNames(this.query).forEach((key) => {
          this.query[key] = null
        })
        this.handleTableChange(this.pagination)
      },
      // 新增/修改数据
      add() {
        // 复制一份数据
        const _formData = { ...this.formData }
        if (_formData.name === CONFIG_KEY.BACKGROUND_LIST) {
          var arr = []
          for (const val of _formData.valueArr) {
            if (val.value) {
              arr.push(val.value + '\n')
            }
          }
          _formData.value = JSON.stringify(arr)
          _formData.valueArr = []
        } else if (
          _formData.name === CONFIG_KEY.WEBSITE_SCRIPT ||
          _formData.name === CONFIG_KEY.WEBSITE_HEAD
        ) {
          var temp = ''
          for (const val of _formData.valueArr) {
            if (val.value) {
              temp += val.value + '\n'
            }
          }
          _formData.value = temp
          _formData.valueArr = []
        }
        // 存在id走修改
        if (_formData.id) {
          update(_formData).then(() => {
            this.visible = false
            this.handleTableChange(this.pagination)
          })
        } else {
          add(_formData).then(() => {
            this.visible = false
            this.handleTableChange(this.pagination)
          })
        }
      },
      // 查询数据
      handleTableChange(pagination) {
        const pager = { ...this.pagination }
        pager.current = pagination.current
        this.pagination = pager
        this.fetch()
      },
      // 请求后台
      fetch() {
        this.loading = true
        getList({
          pageSize: this.pagination.pageSize,
          current: this.pagination.current,
          ...this.query,
        }).then(({ data }) => {
          const pagination = { ...this.pagination }
          pagination.total = data.total
          this.loading = false
          this.data = data.records
          console.log(this.data)
          this.pagination = pagination
        })
      },
    },
  }
</script>
<style></style>
